//
//  HJSnowflake.m
//  KaiChat
//
//  Created by lx on 2023/12/6.
//

#import "HJSnowflake.h"

@implementation HJSnowflake{
    NSInteger _datacenterId;
    NSInteger _machineId;
    uint64_t _sequence;
    uint64_t _lastTimestamp;
}

- (instancetype)init {
    return [self initWithDatacenterId:1 machineId:1];
}

- (instancetype)initWithDatacenterId:(NSInteger)datacenterId machineId:(NSInteger)machineId {
    self = [super init];
    if (self) {
        _datacenterId = datacenterId & 0x1F; // 5位
        _machineId = machineId & 0x1F;       // 5位
        _sequence = 0;
        _lastTimestamp = 0;
    }
    return self;
}

- (uint64_t)nextId {
    @synchronized (self) {
        uint64_t timestamp = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
        
        if (timestamp == _lastTimestamp) {
            _sequence = (_sequence + 1) & 0xFFF; // 12位
            if (_sequence == 0) {
                // 当前毫秒内的序列号用尽，等待下一毫秒
                while (timestamp <= _lastTimestamp) {
                    timestamp = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
                }
            }
        } else {
            // 不同毫秒内，序列号重置为0
            _sequence = 0;
        }
        
        // 更新最后一次生成ID的时间戳
        _lastTimestamp = timestamp;
        
        // 生成ID：时间戳（41位） | 数据中心ID（5位） | 机器ID（5位） | 序列号（12位）
        uint64_t snowflakeId = ((timestamp - 1609459200000) & 0x1FFFFFFFFFF) << 22 | (_datacenterId << 17) | (_machineId << 12) | _sequence;
        return snowflakeId;
    }
}



@end
